package server

import (
	hbtp "github.com/mgr9525/HyperByte-Transfer-Protocol"
	"gov-auto-ui/src/comm"
	"os"
	"path/filepath"
	"runtime"
	"time"
)

func Run() error {
	if comm.WorkPath == "" {
		pth := filepath.Join(HomePath(), "001")
		comm.WorkPath = EnvDefault("GOKINS_WORKPATH", pth)
	}
	if !comm.NotUpPass {
		comm.NotUpPass = EnvDefault("GOKINS_NOTUPDATEPASS") == "true"
	}

	os.MkdirAll(comm.WorkPath, 0750)


	go runWeb()

	time.Sleep(time.Millisecond * 10)

	regApi()
	comm.Installed = true

	//go runHbtp()
	hbtp.Infof("go-auto-ui running at %s", comm.WorkPath)
	hbtp.Infof("http://localhost%s", comm.WebHost)

	for !hbtp.EndContext(comm.Ctx) {   //EndContext--启动程序
		time.Sleep(time.Millisecond * 100)
	}
	time.Sleep(time.Second)

	return nil
}

func EnvDefault(nm string, defs ...string) string {
	s := os.Getenv(nm)
	if s == "" && len(defs) > 0 {
		s = defs[0]
	}
	return s
}

func HomePath() string {
	home := ""
	if runtime.GOOS == "windows" {
		home = os.Getenv("USERPROFILE")
	} else {
		home = os.Getenv("HOME")
	}
	return home
}


